import { Button, List, InputItem, WhiteSpace, WingBlank, Icon, Toast } from 'antd-mobile';
import React, { Component } from 'react';
import { Text, View, Image, StyleSheet, AppRegistry, AsyncStorage } from 'react-native';
import { NavigationActions } from 'react-navigation'
import { Urls } from '../utils/Urls'
import JPushModule from 'jpush-react-native';

const resetAction = NavigationActions.reset({
  index: 0,
  actions: [
    NavigationActions.navigate({ routeName: 'MainScreenNavigator', params: { token: '123456' } })
  ]
})
export class LoginScreen extends React.Component {
  componentDidMount() {
    AsyncStorage.getItem('username', (error, result) => {
      if (!error) {
        this.setState({
          username: result
        });
      }
    })
    AsyncStorage.getItem('password', (error, result) => {
      if (!error) {
        this.setState({
          password: result
        });
      }
    })
  }
  // handleClick = () => {
  // this.customFocusInst.focus();
  handleClick() {
    const { navigate } = this.props.navigation;
    // var formData = new FormData();
    // formData.append('username', this.state.username);
    // formData.append('password', this.state.password);
    var opts = {
      method: "POST",
      headers: {
        'Content-Type': 'application/x-www-form-urlencoded'
      },
      body: "username=" + this.state.username + "&password=" + this.state.password
    }

    let url = Urls.LOGIN;
    fetch(url, opts)
      .then((response) => {
        // 如果登录成功，那么路由重置
        console.log(response)
        let resBody = JSON.parse(response._bodyText);
        if (resBody.code == 0) {
          // 如果已经关注的变电站数>0
          if (resBody.content && resBody.content.length > 0) {
            this.props.navigation.dispatch(resetAction);

            let tagStr = [];
            resBody.content.forEach(element => {
              tagStr.push(element + "")
            });
            JPushModule.setTags(tagStr, success => {
              console.log("设置标签: ", success);
              return false;
            })
          } else {
            this.props.navigation.navigate('ChooseStationScreen', { "title": "请先勾选关注的变电站" });
          }
        } else {
          Toast.fail('用户名或密码错误', 1);
        }
      })
      .catch((error) => {
        Toast.fail('请检查网络连接', 1);
        console.log(error);
      })
    // navigate.reset('MainScreenNavigator', { username: this.state.username, password: this.state.passwd })
  }
  static navigationOptions = {
    header: null
  };
  state = {
    username: '',
    password: '',
  }
  onChange1 = (username) => {
    this.setState({
      username,
    });
    AsyncStorage.setItem('username', username, (error) => {});
  }
  onChange2 = (password) => {
    this.setState({
      password,
    });
    AsyncStorage.setItem('password', password, (error) => {});
  }

  render() {
    const { navigate } = this.props.navigation;
    return (
      <View>
        <Image
          source={require('../assets/Images/logo.png')}
          style={styles.imagestyle}
        />
        <WingBlank size="lg">
          <List >

            <InputItem
              style={{ height: 52, borderColor: 'gray' }}
              clear
              placeholder="请输入用户名"
              // ref={el => this.autoFocusInst = el}
              // v-model="this.state.username"
              onChange={this.onChange1}
              value={this.state.username}
            // type="text"
            >账号：</InputItem>
          </List>
          <WhiteSpace /><WhiteSpace />
          <List>
            <InputItem
              style={{ height: 52 }}
              clear
              placeholder="请输入密码"
              // onChangeText={(password) => this.setState({password})}
              // v-model="this.state.passwd"
              onChange={this.onChange2}
              value={this.state.password}
              type="password"
            >密码：</InputItem>
          </List>
          <WhiteSpace /><WhiteSpace /><WhiteSpace /><WhiteSpace />
          <Button
            type="primary" inline size="large"
            // onClick={() => navigate('MainScreenNavigator', { username: this.state.username,password: this.state.passwd })}
            onClick={this.handleClick.bind(this)}
          >登录</Button>
          <WhiteSpace size="lg" /><Text onPress={() => navigate('RegisterScreen')}>去注册</Text>
        </WingBlank>
      </View>
    );
  }
}
const styles = StyleSheet.create({
  imagestyle: {
    width: 128,
    height: 128,
    marginTop: 48,
    marginBottom: 48,
    alignSelf: 'center'
  }
});
// ‪E:\AndroidSDK\tools\emulator.exe -netdelay none -netspeed full -avd Nexus_5X_API_23